class SessionsController < ApplicationController
  
  def authorize
      
  end
  
  def close_browser_remind
    session[:close_browser_remind] = true
    render :status => 200, :text => 'success'
  end
  
  def new 
    @http_referer = params[:http_referer].present? ? params[:http_referer] : request.referer
    @http_referer = nil if @http_referer.try(:match,'/homes/default')
    @session = {}
    def @session.enterprise_name      
    end
    def @session.mobile      
    end
    def @session.password
    end
    def @session.remember_me
      'no'
    end
  end
  
  def create
    @http_referer = params[:http_referer] if params[:http_referer].present?          
    if User.authenticate(params[:session])
      session[:current_user_id] = User.find_by_enterprise_name_and_mobile_encrypted_password(params[:session]).id
      # remember me
      if params[:session][:remember_me] == 'yes'
        cookies.signed[:user_id] = {
          :value => current_user_id.to_s,
          :expires => 10.years.from_now
        }
        cookies.signed[:user_security_key] = {
          :value => current_user.security_key_in_cookies,
          :expires => 10.years.from_now
        }
      else
        clear_login_info_from_cookies
      end      
      redirect_to(@http_referer || user_url(current_user))
    else
      clear_login_info_from_cookies
      @login_failed = true      
      @session = params[:session]
      def @session.enterprise_name
        self[:enterprise_name]
      end
      def @session.mobile      
        self[:mobile]
      end
      def @session.password
      end
      def @session.remember_me
        self[:remember_me]
      end      
      render :action => :new
    end
  end
  
  def destroy
    session.delete :current_user_id
    clear_login_info_from_cookies
    redirect_to new_session_url
  end

  private
  def clear_login_info_from_cookies
    cookies.delete :user_id
    cookies.delete :user_security_key
  end  
end
